<template>
  <div class="main-container">
    <a-card class="layout-card">
      <a-row align="middle" justify="space-between">
        <SearchGroup
          :label-option="labelOption"
          @handleSearch="loadData(1)"
          @handleReset="reset"
          :searchOption="filterOption"
        />
        <a-col>
          <a-button class="btn" type="primary" @click="showModal"> <plus-outlined />新建 </a-button>
        </a-col>
      </a-row>
      <a-table
        :scroll="{ x: 1450 }"
        class="tablstyle"
        bordered
        rowKey="roleId"
        :dataSource="list"
        :columns="columns"
        :pagination="false"
        :loading="loading"
      >
        <template #index="{ index }">
          {{ index + 1 }}
        </template>
        <template #bodyCell="{ column, record, index, text }">
          <template v-if="column.key === 'index'">
            <span>{{ index + 1 }}</span>
          </template>
          <template v-if="column.key === 'xymc'">
            <span>{{ text }}</span>
          </template>
          <template v-if="column.key === 'operation'">
            <a-button type="link" @click="showModal(record)">编辑</a-button>
            <a-popconfirm
              :title="record.roleState == 'NORMAL' ? '确认禁用吗?' : '确认启用吗?'"
              @confirm="conclose(record)"
            >
              <a-button
                type="link"
                :disabled="record.createType == 'SYS'"
                :danger="record.roleState == 'NORMAL'"
              >
                {{ record.roleState == 'NORMAL' ? '禁用' : '启用' }}
              </a-button>
            </a-popconfirm>
            <a-button
              type="link"
              :disabled="record.createType == 'SYS'"
              danger
              @click="handleDel([record.roleId])"
            >
              删除
            </a-button>
          </template>
        </template>
      </a-table>

      <a-pagination
        :show-total="total => `共 ${total} 条`"
        :show-size-changer="false"
        show-quick-jumper
        v-model:current="curPage"
        v-model:pageSize="pageSize"
        :total="total"
      />
    </a-card>

    <a-modal
      v-model:visible="visible"
      :title="formStore.roleId ? '编辑角色' : '新增角色'"
      @ok="handelAllot"
      :width="450"
      @cancel="handelCancel"
      :maskClosable="false"
    >
      <a-form :model="formStore" class="form" ref="form">
        <a-form-item label="角色名称" name="roleName">
          <a-input
            :disabled="formStore.createType == 'SYS'"
            v-model:value="formStore.roleName"
          ></a-input>
        </a-form-item>
        <a-form-item label="备注" name="remark">
          <a-input
            :disabled="formStore.createType == 'SYS'"
            v-model:value="formStore.remark"
          ></a-input>
        </a-form-item>
        <a-form-item label="权限设置" name="state">
          <div class="max-h-[35vh] overflow-y-auto">
            <a-tree
              v-model:checkedKeys="formStore.checked"
              checkable
              checkStrictly
              :tree-data="treeData"
              @check="checkSele"
              :field-names="{ key: 'menuId' }"
            ></a-tree>
          </div>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>
<script lang="ts" setup>
import { dateUtil } from '/@/utils/dateUtil'
import { cloneDeep } from 'lodash-es'
import { ref, reactive, onMounted } from 'vue'
import { useMessage } from '/@/hooks/web/useMessage'
import { getAuthCache } from '/@/utils/auth'
import {
  setStatus,
  delFun,
  getRoleInfo,
  getAccountNumberList,
  allotSubject,
} from '/@/api/system-manage/teacher-info'
import { isArray } from '/@/utils/is'
import { delConfirm } from '/@/hooks/web/useCommonMessage'

import { useList } from '/@/hooks/web/useList'

const { createMessage } = useMessage()
const columns = ref([
  {
    title: '序号',
    dataIndex: 'index',
    key: 'index',
    align: 'center',
    width: 80,
    fixed: true,
  },
  {
    title: '角色名称',
    dataIndex: 'roleName',
    key: 'roleName',
    align: 'center',
  },
  {
    title: '角色类型',
    dataIndex: 'createType',
    key: 'createType',
    align: 'center',
    customRender: ({ text }) => {
      return text == 'SYS' ? '系统角色' : '自定义角色'
    },
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
    align: 'center',
    customRender: params => {
      return dateUtil(params.text).format('YYYY-MM-DD HH:mm')
    },
  },
  {
    title: '备注',
    dataIndex: 'remark',
    key: 'remark',
    align: 'center',
  },
  {
    title: '状态',
    dataIndex: 'roleState',
    key: 'roleState',
    align: 'center',
    width: 80,
    customRender: params => {
      if (!isArray(labelOption.value[1].selectOption)) return '--'
      let arr = labelOption.value[1].selectOption.filter(e => e.dictCode == params.value)
      if (arr.length) return arr[0].dictName
      return '--'
    },
  },
  {
    title: '操作',
    dataIndex: 'operation',
    key: 'operation',
    align: 'center',
    width: 260,
    fixed: 'right',
  },
])

const treeData = ref([])

const visible = ref(false)
const formStore = ref<any>({
  roleId: null,
  roleName: null,
  remark: null,
  checked: { checked: [] },
})

// 树处理
const checkSele = (checkedKeys, e) => {
  checkSeleset(checkedKeys.checked, e.node.children, e.checked, e.node?.parent?.nodes)
}
const checkSeleset = (arr, arr2, checked, parent = []) => {
  if (checked) {
    if (parent.length) {
      for (let i = 0; i < parent.length; i++) {
        if (!arr.includes(parent[i]?.menuId)) {
          arr.push(parent[i]?.menuId)
        }
      }
    }
  } else {
    for (let i = 0; i < arr2.length; i++) {
      let num = arr.indexOf(arr2[i]?.menuId)
      if (num > -1) {
        arr.splice(num, 1)
      }
      if (arr2[i].children && arr2[i].children.length) {
        checkSeleset(arr, arr2[i]?.children || [], checked)
      }
    }
  }
}

// 列表数据
const { reset, loadData, filterOption, loading, curPage, total, pageSize, list } =
  useList(getAccountNumberList)

const labelOption = ref<any>([
  { name: '角色名称', key: 'roleName', inputWidth: 150, labelWidth: 70 },
  {
    name: '状态',
    key: 'roleState',
    selectOption: [],
    inputWidth: 150,
    labelWidth: 50,
  },
])

// 新增修改
const handelAllot = async () => {
  try {
    const { code, message } = await allotSubject({
      ...formStore.value,
      roleMenuIdList: formStore.value.checked.checked || formStore.value.checked,
    })
    if (code == 200) {
      createMessage.info('处理成功')
      loadData()
      visible.value = false
    } else {
      createMessage.error(message)
    }
  } catch (error) {}
}

// 查看/修改详情
const showModal = async row => {
  if (row?.roleId) {
    formStore.value = cloneDeep(row)
    let { code, data } = await getRoleInfo({ roleId: row.roleId })
    if (code == 200) {
      formStore.value.checked = data
    }
  } else {
    formStore.value = {
      checked: [],
      roleId: null,
      roleName: null,
      remark: null,
    }
  }
  visible.value = true
}
// 关闭查看页面
const handelCancel = async () => {
  formStore.value = cloneDeep({})
  visible.value = false
}

// 修改状态
const conclose = async record => {
  try {
    let { code, message } = await setStatus({
      roleId: record.roleId,
      operateState: record.roleState == 'BAN',
    })
    if (code == 200) {
      record.roleState = record.roleState == 'BAN' ? 'NORMAL' : 'BAN'
    } else {
      createMessage.error(message)
    }
  } catch (err) {
    console.log(err)
  }
}
// 删除
const handleDel = todoList => {
  delConfirm(
    delFun,
    {
      todoList,
    },
    loadData
  )
}

// 菜单显示编辑
const handleArrtitle = arr => {
  arr.forEach(ele => {
    if (ele.children) {
      handleArrtitle(ele.children)
    }
    if (ele.menuType == 'button') {
      ele.title = `${ele.title}`
    }
  })
}

import { getDictionaryList } from '/@/views/teacher/home/index'

onMounted(async () => {
  labelOption.value[1].selectOption = await getDictionaryList('state')
  treeData.value = getAuthCache('routeListMoun')
  treeData.value = treeData.value.filter(ele => !!ele.menuId)
  handleArrtitle(treeData.value)
})
</script>
<style lang="less" scoped>
.main-container {
  // height: @c_height;
}

.btn {
  margin-right: 20px;
}

.tablstyle {
  padding: 15px 0;
}

.form {
  padding: 20px;
}
</style>
